// pages/discount/index.js
var userInfo = wx.getStorageSync('userInfo');
var url = getApp().globalData.ApiUrl;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar: 'https://www.zhuisushangcheng.com/data/upload/applet/avatar.png',
    nickName: '未登录',
    coupounsNum: '',
    pintuan_list: [],    // 热门拼团商品列表
    isShow: false,
    page: 10,
    curpage: 1,
    scrollTop: 0,
    scrollHeight: 0,
    price: 19,      // 拼团商品固定价格
    list: [],         // 专区拼团商品列表
    hots: 1,       // hots为1是热门商品 没有就不传
    showView: false,
    num: 1,
    goods_details: {}, //商品详情
    goods_price: '', // 商品价格
    goods_storage: '', //商品库存
    goods_img: '',
    propertyChildNames: '',
    person: "",   // 分享红包人id
    secretkey: "",  // 红包分享比对密钥
    fen_id: 0,
    fen_url: '',
    share_price: '',  // 分享的金额
    showModalStatus: false,
    showNine: false,   // 19元拼团专区
  },
  toDetailsTap: function (e) {
    var dataset = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + dataset.goods_id,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userInfo = wx.getStorageSync('userInfo');
    var that = this;
    that.setData({
      avatar: userInfo.avatarUrl,
      nickName: userInfo.nickName
    });
    that.getList('unused');
    that.getPintuanList();

    // 获取固定价格的商品
    wx.request({
      url: url + '/mobile/index.php?act=api&op=get_pintuan_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        price: that.data.price
      },
      success: (res) => {
        if (res.data.code == 200) {
          var list = res.data.datas;
          var arr = [];
          for (var i in list) {
            arr.push(list[i]);
          }
          if (arr.length == 0) {
            that.setData({
              showNine: false
            })
          }
          this.setData({
            list: arr
          })
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
        })
      }
    });

    // 获取188优惠券图片
    wx.request({
      url: url + '/mobile/index.php?act=api&op=get_banner',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        banner_id: app.globalData.uer_center,
      },
      success: (res) => {
        if (res.data.code == 200) {
          var list = res.data.datas;
          for (var i in list) {
            var arr = list[i].adv_url;
            var img_url = list[i].adv_content;
            var red_id = arr.replace(/[^0-9]/ig, "");
          }
          this.setData({
            img_url: url + img_url,
            red_url: arr,
            red_id: red_id
          })
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
        })
      }
    })
    // 获取分享红包id地址
    wx.request({
      url: url + '/mobile/index.php?act=api&op=get_banner',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        banner_id: app.globalData.discount_red
      },
      success: (res) => {
        if (res.data.code == 200) {
          var arr = [];
          for (var i in res.data.datas) {
            arr.push(res.data.datas[i]);
            var fen_id = arr[i].adv_url.replace(/[^0-9]/ig, "");
            var share_url = arr[i].adv_url;
          }
          this.setData({
            fen_id: fen_id,
            fen_url: arr[i].adv_url,
            red_list: res.data.datas,
            share_url: share_url
          })
        };
        if (res.data.code == 400) {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //点击头像跳转登录
  toLogin: function () {
    var that = this;
    var key = wx.getStorageSync('key');
    if (!key) {
      wx.navigateTo({
        url: '/pages/authorize/index',
      });
    }
  },
  //跳转优惠券使用页面
  toUse: function () {
    wx.navigateTo({
      url: '/pages/mycoupons/index'
    });
  },
  // 获取红包分享时获得的参数
  shareBtn: function(e) {
    getApp().saveFormId(e.detail.formId);
    var key = wx.getStorageSync("key");
    wx.showLoading({
      title: '加载中,请稍后...',
      mask: true,
    });
    wx.request({
      url: url + '/mobile/index.php?act=member_redpacket&op=get_share_parameter',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: "GET",
      dataType: "json",
      data: {
        key: key,
        rpacket_t_id: this.data.fen_id,
      },
      success: (res) => {
        if (!key) {
          wx.navigateTo({
            url: '/pages/authorize/index',
          })
        };
        if (res.data.code == 200) {
          wx.hideLoading();
          this.setData({
            person: res.data.datas.redpacket_share_person,   // 分享红包人id
            secretkey: res.data.datas.redpacket_share_secretkey,  // 红包分享比对密钥
            showModalStatus: true,
            share_price: res.data.datas.rpacket_t_price
          });
        }
        if (res.data.code == 400) {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      }
    })
  },
  /**
   * 获取热门拼团商品列表
   */
  getPintuanList: function () {
    wx.request({
      url: url + '/mobile/index.php?act=api&op=get_pintuan_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        hots: this.data.hots,
      },
      success: (res) => {
        if (res.data.code == 200) {
          var arr = [];
          var size = this.data.page;
          var curpage = this.data.curpage;   // 数据页码
          for (var i in res.data.datas) {
            arr.push(res.data.datas[i]);
          }
          if (arr.length < size) {
            this.setData({
              pintuan_list: arr,
              page: arr.length,
              curpage: curpage
            })
          } else {
            this.setData({
              pintuan_list: arr,
              page: arr.length,
              curpage: curpage++
            })
          }
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      }
    })
  },
  /**
   * 获取有几张优惠券
   */
  getList: function (state) {
    var that = this;
    var key = wx.getStorageSync("key");
    wx.request({
      url: url + '/mobile/index.php?act=member_redpacket&op=redpacket_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'POST',
      data: {
        key: key,
        rp_state: state
      },
      success: (res) => {
        if (res.data.code == 200) {
          var redpacket_list = res.data.datas.redpacket_list;
          if (redpacket_list.length == 0) {
            that.setData({
              coupounsNum: false,
            });
          } else {
            that.setData({
              coupounsNum: redpacket_list.length,
            });
          }
        };
        if (res.data.code == 400) {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          mask: true,
        });
      }
    });
  },
  /**
   * 关闭弹窗
   */
  errorTap: function () {
    this.setData({
      showView: false,
      propertyChildNames: '',
    });
  },
  /**
	* 获取商品详情
	*/
  getDetails: function (dataset) {
    var that = this;
    //获取商品详情
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_detail',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        goods_id: dataset
      },
      success: (res) => {
        if (res.data.code == 200) {
          var datas = res.data.datas;
          var specObj = res.data.datas.goods_info.spec_name;
          var imgURL = res.data.datas.goods_image.split(',');
          var tmp = {}; //商品规格
          var tmp2 = {}; //商品尺寸
          var specALLArr = []; // 商品贵和和商品
          var goods_spec = [];
          var spec_id = [];
          for (var spec_d in res.data.datas.goods_info.goods_spec) {
            goods_spec.push(res.data.datas.goods_info.goods_spec[spec_d]);  // 商品规格
            spec_id.push(spec_d);
            var spec = goods_spec.toString().replace(/,/g, " ");
          };
          for (var i in specObj) {
            tmp.id = i;
            tmp.name = specObj[i];
            tmp.twoData = [];
            for (var j in res.data.datas.goods_info.spec_value[i]) {
              tmp2.id = j;
              tmp2.name = res.data.datas.goods_info.spec_value[i][j];
              tmp2.propertyID = i;
              tmp2.active = (j in res.data.datas.goods_info.goods_spec) ? true : false;
              tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));
            }
            specALLArr.push(JSON.parse(JSON.stringify(tmp)));
          };
          if (spec) {
            this.setData({
              propertyChildNames: spec,
            })
          };
          that.setData({
            imgUrl: imgURL,
            sum: imgURL.length,
            goods_details: res.data.datas,
            specALLArr: specALLArr,
            detailData: datas,  //商品详情
            buyGoods_id: dataset, //购买的商品价格
            goods_price: datas.goods_info.pintuan_price, //拼团价格
            goods_storage: datas.goods_info.goods_storage, //商品库存
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      }
    });
  },
  /**
   * 切换规格选中状态
   * @author chelfinn
   * @date 2018-09-18
   */
  clickTap: function (e) {
    var that = this;
    var ids = [];   // 选中的id
    var valus = [];  // 选中商品的名字
    var specALLArr = that.data.specALLArr;
    var childs = that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData;
    // 取消该分类下的子栏目所有的选中状态
    for (var i = 0; i < childs.length; i++) {
      that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[i].active = false;
    }
    // 设置当前选中状态
    that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[e.currentTarget.dataset.propertychildindex].active = true;
    that.setData({
      specALLArr: specALLArr
    });
    // 循环数组 获取点中状态时的规格
    for (var id in specALLArr) {
      for (var i in specALLArr[id].twoData) {
        if (specALLArr[id].twoData[i].active == true) {
          ids.push(specALLArr[id].twoData[i].id);  // 获取的商品选中时的id
          valus.push(specALLArr[id].twoData[i].name);   // 获取商品点中时的规格
        }
      };
    };
    var spec_id = ids.sort().join("|");   // 升序
    var spec_value = valus.toString().replace(/,/g, " ");  // 选中的规格
    var spec_list = that.data.detailData.spec_list;
    if (spec_value) {
      this.setData({
        propertyChildNames: spec_value,
      })
    }
    if (spec_id in spec_list) {
      that.setData({
        buyGoods_id: spec_list[spec_id], //获取购买的商品id
      });
      // 获取商品详情
      wx.request({
        url: url + '/mobile/index.php?act=goods&op=goods_detail',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        dataType: 'json',
        method: 'GET',
        data: {
          goods_id: that.data.buyGoods_id,
        },
        success: (res) => {
          if (res.data.code == 200) {
            var datas = res.data.datas;
            var specObj = res.data.datas.goods_info.spec_name;
            var tmp = {}; //商品规格
            var tmp2 = {}; //商品尺寸
            var specALLArr = []; // 商品贵和和商品
            for (var i in specObj) {
              tmp.id = i;
              tmp.name = specObj[i];
              tmp.twoData = [];
              for (var j in res.data.datas.goods_info.spec_value[i]) {
                tmp2.id = j;
                tmp2.name = res.data.datas.goods_info.spec_value[i][j];
                tmp2.propertyID = i;
                tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));
              }
              specALLArr.push(JSON.parse(JSON.stringify(tmp)));
            };
            if (datas.goods_info.pintuan_promotion == 1) {
              that.setData({
                detailData: datas,  //商品详情
                buyGoods_id: datas.goods_info.goods_id, //购买的商品价格
                goods_price: datas.goods_info.pintuan_price, //商品价格
                goods_storage: datas.goods_info.goods_storage, //商品库存
                showView: true,
              })
            } else {
              that.setData({
                detailData: datas,  //商品详情
                buyGoods_id: datas.goods_info.goods_id, //购买的商品价格
                goods_price: datas.goods_info.goods_price, //商品价格
                goods_storage: datas.goods_info.goods_storage, //商品库存
                showView: true
              });
            };
          };
          if (res.data.code == 400) {
            if (res.data.login == 0 && res.data.login) {
              wx.navigateTo({
                url: '/pages/authorize/index',
              })
            } else {
              wx.showToast({
                title: res.data.datas.error,
                icon: 'none',
                duration: 1500,
                mask: true
              })
            };
          }
        },
        fail: () => {
          wx.showToast({
            title: '人太多啦',
            icon: 'none',
            mask: true
          })
        }
      });
    }
  },
  /**
   * @author chelfinn
   * 马上开团--提交订单页面
   */
  toGroupBuying: function (e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var goods_id = e.currentTarget.dataset.goods_id;
    var goods_img = e.currentTarget.dataset.goods_img;
    var mobile = wx.getStorageSync("mobile");
    if (!mobile) {
      wx.navigateTo({
        url: '/pages/phone/index',
      })
    };
    that.setData({
      showView: true,
      goods_img: goods_img,
      dataset: dataset
    });
    that.getDetails(goods_id);
  },
  /**
   * 立即开团
   */
  groupBuyNow: function (e) {
    var that = this;
    /**
     * log_id 参团id,自己发起的团,支付成功后返回的id，有则传，无则不传，不能穿空    pintuan_id 不为空时，为拼主的拼团号
     * pintuan    拼团的话设置为1，默认为空
     * status 1普通购买，2拼团，3秒杀
     */
    var ifcart = '';
    var log_id = '';
    var goods_id = e.currentTarget.dataset.goods_id;
    //item 店铺名，商品名，商品图片，选中规格，商品单价，数量
    var item = {};
    item.store_name = that.data.goods_details.store_info.store_name;
    item.store_id = that.data.goods_details.store_info.store_id;
    item.goods_name = that.data.goods_details.goods_info.goods_name;
    item.goods_price = that.data.goods_price;
    item.spec_name = that.data.propertyChildNames;
    item.goods_freight = that.data.detailData.goods_info.goods_freight;
    item.goods_num = that.data.num;
    item = JSON.stringify(item);
    var totalPrice = e.currentTarget.dataset.pintuan_price;
    var cart_id = goods_id + '|1';
    
    var item1 = JSON.parse(item);
    var storega = that.data.goods_storage;
    var arr = item1.spec_name.split(" ");
    if (this.data.specALLArr.length == 0) {
      if (storega == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他上商品',
          showCancel: false,
        })
        this.setData({
          showView: false
        })
        return;
      }
      wx.navigateTo({
        url: '/pages/submit-order/index?cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_pintuan=1',
      });
    } else {
      if (storega == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他上商品',
          showCancel: false,
        })
        this.setData({
          showView: false
        })
        return;
      }
      if (arr.length != this.data.specALLArr.length) {
        wx.showModal({
          title: '提示',
          content: '请先选择商品规格尺寸哟~',
          showCancel: false,
        });
        return;
      }
      wx.navigateTo({
        url: '/pages/submit-order/index?cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_pintuan=1',
      });
    }
  },
  // 188元优惠券
  getCoupons: function (e) {
    wx.navigateTo({
      url: this.data.red_url,
    });
  },
  // 关闭弹窗
  close: function() {
    this.setData({
      showModalStatus: false
    })
  }, 
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh: function () {
  //   this.getPintuanList(1);
  //   wx.stopPullDownRefresh(); //停止下拉刷新
  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // this.getPintuanList(1);
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var key = wx.getStorageSync("key");
    var red_url = this.data.share_url + '&redpacket_share_person=' + this.data.person + '&redpacket_share_secretkey=' + this.data.secretkey;
    this.share = true;
    return {
      title: userInfo.nickName + '@你,送你一张' +this.data.share_price+ '元优惠券',
      path: red_url,
      imageUrl: 'https://www.zhuisushangcheng.com/data/upload/applet/redImg.png',
      success: (res) => {
        wx.request({
          url: url + '/mobile/index.php?act=member_redpacket&op=share_redpacket_callback_share',
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          method: "POST",
          dataType: "json",
          data: {
            key: key,
            rpacket_t_id: this.data.fen_id,
            redpacket_share_person: this.data.person,
            redpacket_share_secretkey: this.data.secretkey
          },
          success: (res) => {
            if (res.data.code == 200) {
              wx.showToast({
                title: res.data.datas,
                duration: 2000,
              })
              wx.navigateTo({
                url: red_url,
              })
            };
            if (res.data.code == 400) {
              if (res.data.login == 0 && res.data.login) {
                wx.navigateTo({
                  url: '/pages/authorize/index',
                })
              } else {
                wx.showToast({
                  title: res.data.datas.error,
                  icon: 'none',
                  duration: 1500,
                  mask: true
                })
              };
            };
          },
          fail: () => {
            wx.showToast({
              title: '人太多啦',
              icon: 'none',
              mask: true
            })
          }
        });
      },
      fail: () => {
        wx.showToast({
          title: '取消分享',
          icon: 'none',
          mask: true
        })
      }
    }
  },
})